<template>
	<gradient-background>
		<view class="tool-container">
			<view class="tool-content">
				<!-- 工具头部 -->
				<tool-header 
					:icon="toolConfig.icon"
					:title="toolConfig.name"
					:subtitle="toolConfig.description"
					:show-actions="true"
					:show-share="true"
					:show-favorite="true"
					:favorited="isFavorited"
					@share="handleShare"
					@favorite="handleFavorite"
				></tool-header>
				
				<!-- 动态表单区域 -->
				<app-card v-if="formConfig && formConfig.length > 0">
					<view class="input-section">
						<text class="section-title">{{ formTitle || '参数设置' }}</text>
						
						<view 
							v-for="(field, index) in formConfig" 
							:key="field.key"
							class="form-item"
						>
							<text class="form-label">{{ field.label }}</text>
							
							<!-- 文本输入 -->
							<input 
								v-if="field.type === 'text'"
								v-model="formData[field.key]" 
								:placeholder="field.placeholder"
								class="input-field"
							/>
							
							<!-- 多行文本输入 -->
							<textarea 
								v-else-if="field.type === 'textarea'"
								v-model="formData[field.key]" 
								:placeholder="field.placeholder"
								:maxlength="field.maxLength || 200"
								class="textarea-field"
							></textarea>
							
							<!-- 日期选择 -->
							<picker 
								v-else-if="field.type === 'date'"
								mode="date" 
								:value="formData[field.key]" 
								@change="onDateChange($event, field.key)"
								class="date-picker"
							>
								<view class="picker-display">
									<text class="picker-text">{{ getDisplayValue(field.key, field.placeholder) }}</text>
									<text class="picker-arrow">→</text>
								</view>
							</picker>
							
							<!-- 时间选择 -->
							<picker 
								v-else-if="field.type === 'time'"
								mode="time" 
								:value="formData[field.key]" 
								@change="onTimeChange($event, field.key)"
								class="time-picker"
							>
								<view class="picker-display">
									<text class="picker-text">{{ getDisplayValue(field.key, field.placeholder) }}</text>
									<text class="picker-arrow">→</text>
								</view>
							</picker>
							
							<!-- 选择器 -->
							<picker 
								v-else-if="field.type === 'selector'"
								mode="selector" 
								:range="field.options || []" 
								:value="getSelectorIndex(field.key, field.options)"
								@change="onSelectorChange($event, field.key, field.options)"
								class="selector-picker"
							>
								<view class="picker-display">
									<text class="picker-text">{{ getDisplayValue(field.key, field.placeholder) }}</text>
									<text class="picker-arrow">→</text>
								</view>
							</picker>
							
							<!-- 多选组 -->
							<view 
								v-else-if="field.type === 'checkbox'"
								class="checkbox-group"
							>
								<view 
									v-for="option in field.options" 
									:key="option.value"
									class="checkbox-item"
									:class="{ active: isOptionSelected(field.key, option.value) }"
									@tap="toggleOption(field.key, option.value)"
								>
									<text class="checkbox-text">{{ option.label }}</text>
								</view>
							</view>
							
							<!-- 性别选择 -->
							<view 
								v-else-if="field.type === 'gender'"
								class="gender-selector"
							>
								<view 
									class="gender-item"
									:class="{ active: formData[field.key] === 'male' }"
									@tap="selectGender(field.key, 'male')"
								>
									<text class="gender-icon">👨</text>
									<text class="gender-text">男</text>
								</view>
								<view 
									class="gender-item"
									:class="{ active: formData[field.key] === 'female' }"
									@tap="selectGender(field.key, 'female')"
								>
									<text class="gender-icon">👩</text>
									<text class="gender-text">女</text>
								</view>
							</view>
						</view>
					</view>
				</app-card>
				
				<!-- 操作按钮 -->
				<view class="action-section">
					<app-button 
						:text="loading ? loadingText : actionText || '开始分析'" 
						type="primary"
						@tap="handleSubmit"
						:disabled="!canSubmit || loading"
						:loading="loading"
					></app-button>
				</view>
				
				<!-- 结果显示区域 -->
				<view v-if="showResult && resultData" class="result-container">
					<slot name="result" :data="resultData">
						<!-- 默认结果显示 -->
						<app-card>
							<view class="result-section">
								<text class="section-title">分析结果</text>
								<view class="result-content">
									<text class="result-text">{{ resultData.description || '分析完成' }}</text>
								</view>
							</view>
						</app-card>
					</slot>
				</view>
			</view>
		</view>
	</gradient-background>
</template>

<script>
import GradientBackground from '@/components/gradient-background/gradient-background.vue'
import ToolHeader from '@/components/tool-header/tool-header.vue'
import AppCard from '@/components/app-card/app-card.vue'
import AppButton from '@/components/app-button/app-button.vue'
import UserStateManager from '@/utils/user-state-manager.js'

export default {
	name: 'ToolDetailTemplate',
	components: {
		GradientBackground,
		ToolHeader,
		AppCard,
		AppButton
	},
	props: {
		// 工具配置
		toolConfig: {
			type: Object,
			required: true,
			default: () => ({
				icon: '🔧',
				name: '工具',
				description: '工具描述'
			})
		},
		
		// 表单配置
		formConfig: {
			type: Array,
			default: () => []
		},
		
		// 表单标题
		formTitle: {
			type: String,
			default: '参数设置'
		},
		
		// 操作按钮文本
		actionText: {
			type: String,
			default: '开始分析'
		},
		
		// 加载中文本
		loadingText: {
			type: String,
			default: '分析中...'
		},
		
		// 是否显示结果
		showResult: {
			type: Boolean,
			default: false
		},
		
		// 结果数据
		resultData: {
			type: Object,
			default: null
		},
		
		// 是否加载中
		loading: {
			type: Boolean,
			default: false
		},
		
		// 验证规则
		validationRules: {
			type: Object,
			default: () => ({})
		}
	},
	data() {
		return {
			formData: {},
			isFavorited: false
		}
	},
	computed: {
		canSubmit() {
			// 检查必填字段
			const requiredFields = this.formConfig.filter(field => field.required)
			return requiredFields.every(field => {
				const value = this.formData[field.key]
				if (field.type === 'checkbox') {
					return value && value.length > 0
				}
				return value && value.toString().trim().length > 0
			})
		}
	},
	mounted() {
		this.initFormData()
		this.autoFillUserInfo()
		this.checkFavoriteStatus()
	},
	methods: {
		// 初始化表单数据
		initFormData() {
			const data = {}
			this.formConfig.forEach(field => {
				if (field.type === 'checkbox') {
					data[field.key] = []
				} else if (field.type === 'date') {
					data[field.key] = field.defaultValue || ''
				} else {
					data[field.key] = field.defaultValue || ''
				}
			})
			this.formData = data
		},
		
		// 自动填写用户信息
		autoFillUserInfo() {
			const autoFillInfo = UserStateManager.getAutoFillInfo()
			if (!autoFillInfo) return
			
			// 根据字段映射自动填写
			const fieldMapping = {
				name: ['name', 'userName', 'personName'],
				gender: ['gender', 'sex'],
				birthday: ['birthday', 'birthDate', 'birth'],
				phone: ['phone', 'mobile', 'phoneNumber']
			}
			
			Object.keys(fieldMapping).forEach(infoKey => {
				const fieldNames = fieldMapping[infoKey]
				fieldNames.forEach(fieldName => {
					if (this.formData.hasOwnProperty(fieldName) && autoFillInfo[infoKey]) {
						this.formData[fieldName] = autoFillInfo[infoKey]
					}
				})
			})
		},
		
		// 检查收藏状态
		checkFavoriteStatus() {
			// 从本地存储检查是否已收藏此工具
			uni.getStorage({
				key: 'favorite_tools',
				success: (res) => {
					const favoriteTools = res.data || []
					this.isFavorited = favoriteTools.includes(this.toolConfig.id)
				},
				fail: () => {
					this.isFavorited = false
				}
			})
		},
		
		// 获取显示值
		getDisplayValue(key, placeholder) {
			const value = this.formData[key]
			return value || placeholder
		},
		
		// 获取选择器索引
		getSelectorIndex(key, options) {
			const value = this.formData[key]
			if (!value || !options) return 0
			return options.indexOf(value)
		},
		
		// 检查选项是否被选中
		isOptionSelected(key, value) {
			const selected = this.formData[key] || []
			return selected.includes(value)
		},
		
		// 事件处理
		onDateChange(e, key) {
			this.formData[key] = e.detail.value
		},
		
		onTimeChange(e, key) {
			this.formData[key] = e.detail.value
		},
		
		onSelectorChange(e, key, options) {
			const index = e.detail.value
			this.formData[key] = options[index]
		},
		
		toggleOption(key, value) {
			const selected = this.formData[key] || []
			const index = selected.indexOf(value)
			if (index > -1) {
				selected.splice(index, 1)
			} else {
				selected.push(value)
			}
			this.formData[key] = [...selected]
		},
		
		selectGender(key, gender) {
			this.formData[key] = gender
		},
		
		// 表单提交
		handleSubmit() {
			if (!this.canSubmit) {
				uni.showToast({
					title: '请完善必填信息',
					icon: 'none'
				})
				return
			}
			
			// 数据验证
			const validationResult = this.validateForm()
			if (!validationResult.valid) {
				uni.showToast({
					title: validationResult.message,
					icon: 'none'
				})
				return
			}
			
			// 发射提交事件
			this.$emit('submit', this.formData)
		},
		
		// 表单验证
		validateForm() {
			// 基础验证已在 canSubmit 中完成
			// 这里可以添加更复杂的验证逻辑
			return { valid: true }
		},
		
		// 分享功能
		handleShare() {
			this.$emit('share', this.toolConfig)
		},
		
		// 收藏功能
		handleFavorite(favorited) {
			uni.getStorage({
				key: 'favorite_tools',
				success: (res) => {
					let favoriteTools = res.data || []
					if (favorited) {
						if (!favoriteTools.includes(this.toolConfig.id)) {
							favoriteTools.push(this.toolConfig.id)
						}
					} else {
						favoriteTools = favoriteTools.filter(id => id !== this.toolConfig.id)
					}
					
					uni.setStorage({
						key: 'favorite_tools',
						data: favoriteTools,
						success: () => {
							this.isFavorited = favorited
							uni.showToast({
								title: favorited ? '已收藏' : '已取消收藏',
								icon: 'success'
							})
						}
					})
				},
				fail: () => {
					// 首次使用，创建收藏列表
					const favoriteTools = favorited ? [this.toolConfig.id] : []
					uni.setStorage({
						key: 'favorite_tools',
						data: favoriteTools,
						success: () => {
							this.isFavorited = favorited
							uni.showToast({
								title: favorited ? '已收藏' : '已取消收藏',
								icon: 'success'
							})
						}
					})
				}
			})
		}
	}
}
</script>

<style lang="scss" scoped>
@import '@/styles/tool-theme.scss';

.result-container {
	margin-top: 24rpx;
}

.result-content {
	.result-text {
		font-size: 28rpx;
		color: #000000;
		line-height: 1.6;
	}
}

// 性别选择器
.gender-selector {
	display: flex;
	gap: 16rpx;
	
	.gender-item {
		flex: 1;
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 20rpx;
		border: 2rpx solid #f0f0f0;
		border-radius: 12rpx;
		background-color: #fafafa;
		transition: all 0.3s ease;
		
		&.active {
			border-color: #6A82FB;
			background: linear-gradient(135deg, #6A82FB 0%, #FC5C7D 100%);
			
			.gender-icon,
			.gender-text {
				color: white;
			}
		}
		
		.gender-icon {
			font-size: 32rpx;
			margin-bottom: 8rpx;
		}
		
		.gender-text {
			font-size: 24rpx;
			color: #000000;
		}
	}
}

// 多选组
.checkbox-group {
	display: flex;
	flex-wrap: wrap;
	gap: 12rpx;
	
	.checkbox-item {
		padding: 12rpx 20rpx;
		border: 2rpx solid #f0f0f0;
		border-radius: 20rpx;
		background-color: #fafafa;
		transition: all 0.3s ease;
		
		&.active {
			border-color: #6A82FB;
			background-color: #6A82FB;
			
			.checkbox-text {
				color: white;
			}
		}
		
		.checkbox-text {
			font-size: 24rpx;
			color: #000000;
		}
	}
}
</style>